package com.ty.superapi.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ty.superapi.entity.Api;
import com.ty.superapi.entity.Project;
import com.ty.superapi.service.ApiService;
import com.ty.superapi.service.ProjectService;
import com.ty.superapi.service.UserService;
import com.ty.superapi.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tianyu
 * @since 2017-12-21
 */
@RestController
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ApiService apiService;

    @Autowired
    private UserService userService;

    /**
     * 查询项目列表
     *
     * @return
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(HttpServletRequest request) {
        Integer userId = userService.getIdFromToken(request.getHeader("token"));
        List<Map<String, Object>> list = projectService.selectByUserId(userId);
        return Result.success(list);
    }

    /**
     * 查询项目信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "get", method = RequestMethod.GET)
    public String get(Integer id) {
        Map<String, Object> projectMap = projectService.selectById(id);
        return Result.success(projectMap);
    }

    /**
     * 新增或修改项目
     *
     * @param project
     * @param userIds
     * @return
     */
    @RequestMapping(value = "put", method = RequestMethod.POST)
    public String put(@Valid Project project, String userIds) {
        projectService.put(project, userIds);
        return Result.success();
    }

    /**
     * 删除项目
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "del", method = RequestMethod.GET)
    public String del(Integer id) {
        projectService.deleteById(id);
        EntityWrapper<Api> entityWrapper = new EntityWrapper<Api>();
        entityWrapper.eq("project_id", id);
        apiService.delete(entityWrapper);
        return Result.success();
    }
}
